<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>班级积分系统</title>
    <style>
        body { font-family: Arial, sans-serif; text-align: center; background-color: #e8f5e9; }
        .container { width: 90%; margin: auto; }
        .group-row {
            display: flex;
            justify-content: start;
            gap: 10px;
            flex-wrap: wrap;
            margin-bottom: 20px;
        }
        .student { 
            padding: 10px; 
            background: #b3e0ff; 
            border-radius: 10px;
            text-align: center;
            width: 22%; /* 每个学生的宽度，最多4个一行 */
        }
        button { margin-top: 5px; }
        .rewards { margin-top: 20px; }
        .level-buttons { margin-top: 10px; }
        .actions { margin-bottom: 20px; }
    </style>
</head>
<body>
    <h1>邓老师积分兑换系统</h1>    <button onclick="resetPoints()">重置积分</button>  <!-- 新添加的重置按钮 -->
    <div class="actions">
        <button onclick="batchChangePoints(5)">全班+5分</button>
        <button onclick="batchChangePoints(-5)">全班-5分</button>
        <button onclick="addStudent()">添加学生</button>
        <select id="groupSelect" onchange="groupChangePoints()">
            <option value="">选择小组</option>
            <option value="1">1组</option>
            <option value="2">2组</option>
            <option value="3">3组</option>
            <option value="4">4组</option>
            <option value="5">5组</option>
            <option value="6">6组</option>
            <option value="7">7组</option>
            <option value="8">8组</option>
            <option value="9">9组</option>
            <option value="10">10组</option>
            <option value="11">11组</option>
            <option value="12">12组</option>
            <option value="13">13组</option>
            <option value="14">14组</option>
            <option value="15">15组</option>            
        </select>
        <button onclick="batchChangeGroupPoints(5)">全组+5分</button>  
        <button onclick="batchChangeGroupPoints(-5)">全组-5分</button>
        <input type="number" id="groupPointsInput" placeholder="输入该组加减分数">
        <button onclick="batchChangeGroupPoints2()">确定</button>
    </div>
    <div id="students" class="container"></div>
    <h2>兑换奖励</h2>
    <input type="text" id="rewardName" placeholder="奖励名称">
    <input type="number" id="rewardCost" placeholder="所需兑换币">
    <button onclick="addReward()">增加奖励</button>
    <select id="studentSelect"></select>
    <div id="rewards" class="rewards"></div>

    <script>
        let studentNames = ["丁姝娴", "李逯轩", "张朵", "徐欣", "牛博言", "杨声瑞", "任有澎", "焦雨欣", "杨语蕊", "杜娟娟", 
            "付怡冉", "孙彦雯", "刘吉研", "刘重仪", "陈煜晗", "王毓婕", "张紫艺", "王美旨", "任轩谊", "韩家鑫", 
            "崔安哲", "李佳涵", "李皓轩", "张继沧", "刘欣宁", "韩紫莹", "崔智超", "姜梦露", "崔舒芯", "陈政举", 
            "刘墺汉", "赵一彤", "桑庆征", "张沛苒", "刘炎炎", "陈悠琪", "崔佳诚", "丁豪杰", "周鹏宇", "李子豪", 
            "杨一统", "崔旭强", "刘雨晴", "田雨馨", "刘雨彤", "陈紫芸", "丁志博", "杜珈辉", "陈京丽", "李广宇", "孙树鹏"];
        
        let students = JSON.parse(localStorage.getItem("students")) || studentNames.map((name, i) => ({
            id: i + 1,
            name,
            points: 0,
            coins: 0,
            seat: i + 1, 
            group: Math.ceil(Math.random() * 5),  // 随机分配小组
            level: "C"  // 初始时默认为C类
        }));
        let rewards = JSON.parse(localStorage.getItem("rewards")) || [];

        function updateStorage() {
            localStorage.setItem("students", JSON.stringify(students));
            localStorage.setItem("rewards", JSON.stringify(rewards));
        }

        function renderStudents() {
            let groupedStudents = groupBy(students, 'group'); // 按小组分组
            let html = '';
            Object.keys(groupedStudents).sort((a, b) => a - b).forEach(group => {
                html += `<div class="group-row">
                            <h2> 第${group}组</h2>
                            ${groupedStudents[group].sort((a, b) => {
                                return getLevelOrder(a.level) - getLevelOrder(b.level); // 按等级排序
                            }).map(s => `<div class="student">
                                <p><h1>${s.name}</h1> 学号:${s.seat} </p>
                                <p>总积分: ${s.points} , 剩余兑换币: ${s.coins}</p>
                                <p>第${s.group}组 , 等级: ${s.level}</p>
                                <button onclick='changePoints(${s.id}, 1)'>+1</button>
                                <button onclick='changePoints(${s.id}, -1)'>-1</button>
                                <input type="number" id="input-${s.id}" placeholder="输入加减分数">
                                <button onclick='changePointsFromInput(${s.id})'>提交</button>


                                <div class="level-buttons">
                                <button onclick='changeSeat(${s.id})'>调整学号</button>
                                <button onclick='assignGroup(${s.id})'>分配小组</button>
                                    <button onclick='assignLevel(${s.id}, "A")'>A</button>
                                    <button onclick='assignLevel(${s.id}, "B")'>B</button>
                                    <button onclick='assignLevel(${s.id}, "C")'>C</button>
                                    <button onclick='assignLevel(${s.id}, "D")'>D</button>
                                    <button onclick='deleteStudent(${s.id})'>删除该同学!</button>

                                </div>

                            </div>`).join('')}
                        </div>`;
            });
            document.getElementById("students").innerHTML = html;
            renderStudentSelect();
            updateStorage();
        }

        function groupBy(array, key) {
            return array.reduce((result, currentValue) => {
                const groupKey = currentValue[key];
                if (!result[groupKey]) {
                    result[groupKey] = [];
                }
                result[groupKey].push(currentValue);
                return result;
            }, {});
        }

        function getLevelOrder(level) {
            const levelOrder = { "A": 1, "B": 2, "C": 3, "D": 4 };
            return levelOrder[level];
        }

        function renderStudentSelect() {
            let select = document.getElementById("studentSelect");
            select.innerHTML = students.map(s => `<option value='${s.id}'>${s.id}号 ${s.name}</option>`).join('');
        }

        function addStudent() {
            let name = prompt("请输入新学生的姓名:");
            if (name) {
                let newStudent = {
                    id: students.length + 1,
                    name,
                    points: 0,
                    coins: 0,
                    seat: students.length + 1, // 学号跟学生数量一样
                    group: 0,  // 随机分配小组
                    level: "C"  // 初始时默认为C类
                };
                students.push(newStudent);
                renderStudents();
            }
        }

        function batchChangePoints(amount) {
            students.forEach(s => { s.points += amount; s.coins += amount; });
            renderStudents();
            alert("全班分数变更成功！");
        }

        function batchChangeGroupPoints(amount) {
            let group = document.getElementById("groupSelect").value;
            if (group) {
                students.filter(s => s.group === group).forEach(s => {
                    s.points += amount;
                    s.coins += amount;
                });
                renderStudents();
                alert(group + "组分数变更成功！");
            } else {
                alert("请先选择一个小组！");
            }
        }

        function batchChangeGroupPoints2() {
            let group = document.getElementById("groupSelect").value;
            let points = parseInt(document.getElementById("groupPointsInput").value); // 获取输入的分数

            if (group && !isNaN(points)) {
                students.filter(s => s.group === group).forEach(s => {
                    s.points += points;
                    s.coins += points;
                });
                renderStudents();
                alert(group + "组的分数已变更！");
            } else {
                alert("请先选择小组并输入有效的分数！");
            }
        }
    

        function changePoints(id, amount) {
            let student = students.find(s => s.id === id);
            student.points += amount;
            student.coins += amount;
            renderStudents();
            alert("分数变更成功!");
        }

        function changePointsFromInput(id) {
            let student = students.find(s => s.id === id);
            let input = document.getElementById(`input-${id}`).value;
            let points = parseInt(input);
            if (!isNaN(points)) {
                student.points += points;
                student.coins += points;
                renderStudents();
                alert("分数变更成功!");
            } else {
                alert("请输入有效的分数！");
            }
        }

        function deleteStudent(id) {
            if (confirm("确定删除该学生吗？")) {
                students = students.filter(s => s.id !== id);
                renderStudents();
            }
        }

        function sortStudents() {
            students.sort((a, b) => {
                if (a.level === 'A' && b.level !== 'A') return -1;
                if (a.level !== 'A' && b.level === 'A') return 1;
                return a.seat - b.seat;
            });
            renderStudents();
        }

        function addReward() {
            let name = document.getElementById("rewardName").value;
            let cost = parseInt(document.getElementById("rewardCost").value);
            if (name && cost > 0) {
                rewards.push({ name, cost });
                renderRewards();
            }
        }

        function renderRewards() {
            let html = rewards.map((r, index) => `<div>
                <p>${r.name} - ${r.cost}币</p>
                <button onclick='redeemReward(${index})'>兑换</button>
                <button onclick='deleteReward(${index})'>删除</button>
            </div>`).join('');
            document.getElementById("rewards").innerHTML = html;
            updateStorage();
        }

        function redeemReward(index) {
            let cost = rewards[index].cost;
            let selectedId = parseInt(document.getElementById("studentSelect").value);
            let student = students.find(s => s.id === selectedId);
            if (student && student.coins >= cost) {
                student.coins -= cost;
                renderStudents();
                alert("兑换成功！");
            } else {
                alert("兑换币不足");
            }
        }

        function deleteReward(index) {
            if (confirm("确定要删除吗？")) {
                rewards.splice(index, 1);
                renderRewards();
            }

        }

        function changeSeat(id) {
            let student = students.find(s => s.id === id);
            if (student) {
                let newSeat = prompt(`当前学号为${student.seat}，请输入新的学号：`);
                if (newSeat && !isNaN(newSeat)) {
                    student.seat = parseInt(newSeat);
                    renderStudents();
                }
            }
        }

        function assignGroup(id) {
            let student = students.find(s => s.id === id);
            if (student) {
                let group = prompt(`为${student.name}分配小组（例如：1组、2组等）：`);
                if (group) {
                    student.group = group;
                    renderStudents();
                }
            }
        }

        function assignLevel(id, level) {
            let student = students.find(s => s.id === id);
            if (student) {
                student.level = level;
                renderStudents();
            }
        }

        function resetPoints() {
            if (confirm("确定重置学生积分吗？（车长谨慎操作）")) {
                students.forEach(s => {
                    s.points = 0;
                    s.coins = 0;
                });
            renderStudents();
            alert("所有学生的积分和兑换币已重置！");
            }

        }

        renderStudents();
        renderRewards();
    </script>
</body>
</html>
